// 1.创建服务监听端口
// 当发起请求时，先把网页响应回来
// 2.页面发起请求，获取电影列表数据，
// 向我们自己的服务发的请求
// 3.服务端收到获取电影列表请求时，
// 发起http.request，请求猫眼网首页
// 获得猫眼网首页的网页文件代码
// 使用cheerio从网页文件里面提取数据
// 生成电影列表，响应到容户端

const cheerio = require("cheerio");
const http = require("http");
const fs = require("fs");
const path = require("path");
const url = require("url");
const https = require("https");

var reqUrl = "https://maoyan.com/films";

var movieList = [];

http.createServer((req,res)=>{
    var urlObj = url.parse(req.url);
    var pathname = urlObj.pathname;
    if(pathname == '/'){
        var filePath = path.join(__dirname,"/index.html");
        fs.readFile(filePath,(err,data)=>{
            if(err){
                console.log(err);
            }else{
                res.writeHead(200,{"Content-Type":"text/html;charset=utf8"})
                res.write(data);
                res.end();
            }
        })
    }else if(pathname == "getlist"){
        https.get(reqUrl,(resObj)=>{
            var htmlStr = "";
            resObj.on("data",(chunk)=>{
                htmlStr += chunk;
            })
            resObj.on("end",()=>{
                var $ = cheerio.load(htmlStr);
                $(".movie-item-title a").each((i,el)=>{
                    var movieName = $(el).text();
                    var movieId = $(el).attr("data-val");
                    movieId = movieId.slice(movieId.indexOf(":")+1,-1);
                    var num1 = $(el).parent().next().children(".integer").text();
                    var num2 = $(el).parent().next().children(".fraction").text();
                    var rate = num1 + num2;
                    var movieObj = {movieId:movieId,movieName:movieName,movieRate:rate};
                    movieList.push(movieObj);

                })
                res.writeHead(200,{"Content-Type":"text/plain"});
                res.write(JSON.stringify(movieList));
                res.end();
            })
        })
    }
}).listen(8081);